<template>
  <div>
    <el-row v-if="questionDetail.questionType !== 'explain'" style="margin-bottom: 8px;">
      <el-input v-model="questionDetail.caption" placeholder="请输入标题" />
    </el-row>
    <div class="choose-table-function">
      <span style="margin-right:4px;font-size:12px;line-height:20px;">题型选择</span>
      <el-select
        v-model="questionType"
        style="width:100px;margin-right:8px;"
        placeholder="请选择题型"
        size="mini"
        @change="handleTypeChange"
      >
        <el-option-group class="choose-table-function-select" label="选择">
          <el-option label="单选题" value="choice" />
          <el-option label="多选题" value="multiple-choice" />
        </el-option-group>
        <el-option-group class="choose-table-function-select" label="填空">
          <el-option label="填空题" value="fill-blank" />
        </el-option-group>
        <el-option-group class="choose-table-function-select" label="文本">
          <el-option label="段落说明" value="explain" />
        </el-option-group>
      </el-select>
      <span style="margin-right:4px;font-size:12px;line-height:20px;">是否必填</span>
      <el-switch
        v-model="required"
        active-color="#13ce66"
        inactive-color="#ff4949"
      />
    </div>
    <template v-if="questionDetail.questionType === 'explain'">
      <el-row>
        <tinymce v-model="questionDetail.caption" :height="150" placeholder="请输入段落说明" font-size="12px" font-color="#BFC4CC" />
      </el-row>
      <el-row style="height:32px">
        <el-row style="float:right;margin-top:4px;">
          <el-button size="mini" type="success" icon="el-icon-check" circle @click="handleSava" />
          <el-button size="mini" type="danger" icon="el-icon-close" circle @click="handleClose" />
        </el-row>
      </el-row>
    </template>
    <template v-else>
      <vxe-toolbar size="mini">
        <template #buttons>
          <vxe-button type="text" icon="vxe-icon--plus" status="success" @click="handleAdd">新增</vxe-button>
          <vxe-button v-if="questionDetail.questionType === 'fill-blank' || questionDetail.questionType === 'choice'" type="text" icon="vxe-icon--edit-outline question-custom-green" content="设置">
            <template #dropdowns>
              <vxe-button type="text" status="primary" content="设置填空" @click="handleSetFillback" />
              <vxe-button type="text" content="设置换行" @click="handleSetNextline" />
              <vxe-button type="text" content="设置时间" @click="handleSetDate" />
              <vxe-button type="text" content="设置描述" @click="handleSetDescribe" />
            </template>
          </vxe-button>
          <vxe-button type="text" icon="vxe-icon--close" status="danger" @click="handleDeleteRow">删除</vxe-button>
          <vxe-button type="text" icon="vxe-icon--arrow-top" status="warning" @click="handleUp">上移</vxe-button>
          <vxe-button type="text" icon="vxe-icon--arrow-bottom" status="primary" @click="handleDown">下移</vxe-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        :align="'left'"
        :data="questionDetail.questionDetailItemList"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        highlight-current-row
        highlight-hover-row
        border
        resizable
        show-overflow
        size="mini"
        max-height="300"
        @edit-actived="editActivedEvent"
      >
        <vxe-table-column field="indexOrder" title="序号" width="50" />
        <vxe-table-column field="optionName" title="选项名称" :edit-render="{name: 'input', attrs: {type: 'text', placeholder: '请输入选项名称', disabled: optionNameDisabled}}" />
        <vxe-table-column field="optionScore" width="60" title="分值" :edit-render="{}">
          <template #edit="scope">
            <vxe-input v-model="scope.row.optionScore" type="number" placeholder="请输入数值" />
          </template>
        </vxe-table-column>
        <vxe-table-column field="defualt" width="100" title="是否默认" :edit-render="{name: '$select', options: defualtList, props: {clearable: true}, events: {change: handleChange}}" />
      </vxe-table>
      <el-row style="height:32px">
        <el-row style="float:right;margin-top:4px;">
          <el-button size="mini" type="success" icon="el-icon-check" circle @click="handleSava" />
          <el-button size="mini" type="danger" icon="el-icon-close" circle @click="handleClose" />
        </el-row>
      </el-row>
    </template>
  </div>
</template>
<style lang="scss" scope>
.choose-table-function {
  margin-bottom: 8px;
  width: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  padding: 4px 0 4px 8px;
}
.choose-table-function-select {
  .el-select-group__wrap li {
    font-size: 10px !important;
  }
  .el-select-dropdown__item > span {
    font-size: 12px !important;
    line-height: 14px;
  }
}
.question-custom-green {
  color: #008000;
}
.question-custom-green + span {
  color: #008000;
}
</style>

<script>
import { getQuestionById } from '@/api/questionnaire'
import { deleteAnswer } from '@/api/answer'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'ChooseTable',
  components: { Tinymce },
  props: {
    questionDetail: {
      type: Object,
      required: true,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      defualtList: [
        { label: '是', value: '1' },
        { label: '否', value: '0' }
      ],
      questionType: '',
      optionNameDisabled: true,
      required: true,
      questionId: ''
    }
  },
  computed: {
  },
  mounted: function() {
    this.handleOrder()
    this.required = this.questionDetail.required === '1'
    this.questionType = this.questionDetail.questionType
    this.questionId = this.questionDetail.questionId
  },
  methods: {
    // 暂时是给外界赋值用的
    init(questionType, required) {
      this.required = required === '1'
      this.questionType = questionType
    },
    editActivedEvent({ rowIndex, row }) {
      this.optionNameDisabled = row.optionClass === 'fill-blank' || row.optionClass === 'next-line' || row.optionClass === 'date'
    },
    // 设置描述
    handleSetDescribe() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        row.optionClass = ''
      }
    },
    // 设置填空
    handleSetFillback() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        row.optionName = '________'
        row.optionClass = 'fill-blank'
      }
    },
    // 设置换行
    handleSetNextline() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        row.optionName = '换行'
        row.optionClass = 'next-line'
      }
    },
    handleSetDate() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        row.optionName = '日期'
        row.optionClass = 'date'
      }
    },
    async handleTypeChange(current) {
      const temp = JSON.parse(JSON.stringify(this.questionDetail.questionType))
      const that = this
      if (this.questionId && this.questionId !== '' && this.questionDetail.questionType !== 'explain') {
        await getQuestionById({
          questionId: this.questionId
        }).then(r => {
          if (r.data) {
            if (r.data.questionNumber > 0) {
              this.$confirm('切换类型将会导致已填写的问卷该项回答丢失, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 调用删除答卷的接口
                deleteAnswer({
                  detailId: that.questionDetail.detailId
                })
              }).catch(kk => {
                that.questionType = temp
                return
              })
            }
          }
        })
      }
      this.questionDetail.questionType = this.questionType
      // 如果改成单选题
      if (this.questionType === 'choice') {
        const list = this.questionDetail.questionDetailItemList
        list.forEach(item => {
          item.defualt = '0'
        })
      }
    },
    handleChange({ row }) {
      if (this.questionType !== 'choice') {
        return
      }
      const list = this.questionDetail.questionDetailItemList
      if (row) {
        if (row.defualt === '1') {
          list.forEach(item => {
            if (item.indexOrder !== row.indexOrder) {
              item.defualt = '0'
            }
          })
        }
      }
    },
    handleSava() {
      if (!this.questionDetail.caption) {
        this.$message({
          message: '标题不能为空',
          type: 'error'
        })
        return
      }
      if (this.questionType !== 'explain') {
        if (!this.questionDetail.questionDetailItemList || this.questionDetail.questionDetailItemList.length === 0) {
          this.$message({
            message: '选项不能为空',
            type: 'error'
          })
          return
        }
      }
      this.questionDetail.required = this.required ? '1' : '0'
      this.$message({
        message: '保存成功',
        type: 'success'
      })
      this.$emit('close', false)
    },
    // 新增一行
    handleAdd() {
      this.questionDetail.questionDetailItemList.push({
        item_id: '',
        indexOrder: this.questionDetail.questionDetailItemList.length + 1,
        optionName: '',
        optionScore: '',
        defualt: ''
      })
    },
    // 上移
    handleUp() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        const index = row.indexOrder - 1
        if (index === 0) {
          return
        }
        const list = this.questionDetail.questionDetailItemList
        // 在上一项插入该项
        list.splice(index - 1, 0, list[index])
        // 删除后一项
        list.splice(index + 1, 1)
        this.handleOrder()
      }
    },
    // 下移
    handleDown() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        const index = row.indexOrder - 1
        const list = this.questionDetail.questionDetailItemList
        if (index === (list.length - 1)) {
          return
        }
        // 在下一项插入该项
        list.splice(index + 2, 0, (list[index]))
        // 删除前一项
        list.splice(index, 1)
        this.handleOrder()
      }
    },
    // 删除一行 删除元素
    handleDeleteRow() {
      const row = this.$refs.xTable.currentRow
      if (row) {
        this.questionDetail.questionDetailItemList.forEach(function(item, index, arr) {
          if (item.indexOrder === row.indexOrder) {
            arr.splice(index, 1)
          }
        })
        this.handleOrder()
      }
    },
    handleOrder() {
      let index = 1
      this.questionDetail.questionDetailItemList.forEach(item => {
        item.indexOrder = index
        index++
      })
    },
    handleClose() {
      this.$emit('close', true)
    }
  }
}
</script>
